package com.duanyu.mysecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.duanyu.mysecurity.domain.Permission;
import com.duanyu.mysecurity.domain.Users;
import com.duanyu.mysecurity.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    public UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.构造查询条件
        QueryWrapper<Users> queryWrapper = new QueryWrapper();

        //2.查询用户
        Users users = usersMapper.selectOne(queryWrapper.eq("username", username));
        if (users==null){
            return null;
        }

        //3.查询用户权限
        List<Permission> permission = usersMapper.findPermission(username);

        //4.将自定义权限集合转为Security的权限类型集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission1:permission){
            grantedAuthorities.add(new SimpleGrantedAuthority(permission1.getUrl()));
        }

        //返回封装好的UserDetails对象
        return User.withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(grantedAuthorities)
                .build();
    }
}
